package com.hxx.widget.richtext.views

import android.view.KeyEvent
import android.view.View
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.AppCompatEditText
import com.hxx.widget.R
import com.hxx.widget.logi
import com.hxx.widget.richtext.*

/**
 * 富文本编辑器的内容列表适配器
 * 根据功能化分视图样式
 */
open class RichEditorContentAdapter : AbstractRichAdapter(), RichEditor {
    private var requestFocusItem: RichEditorItem? = null
    override fun applyTodoList() {
        requestFocusItem = RichTodoItem()
        data.add(requestFocusItem!!)
        notifyDataSetChanged()
    }

    override fun applySize(level: Int) {
    }

    override fun applyUnderLine() {
    }

    override fun applyBoldStyle() {
    }

    override fun applyItalicsStyle() {
    }

    override fun applyGravityStyle(gravity: TextGravity) {
    }

    override fun applyParagraphStyle() {
    }

    override fun applyColor(color: Int) {
    }

    override fun forward() {
    }

    override fun backoff() {
    }

    override fun onTextBind(item: RichTextItem, view: View, position: Int) {
        view.findViewById<AppCompatEditText>(R.id.widget_rich_text).apply {
        }
    }

    override fun onImageBind(item: RichImageItem, view: View, position: Int) {

    }

    override fun onCheckBoxBind(item: RichTodoItem, view: View, position: Int) {
        val input = view.findViewById<AppCompatEditText>(R.id.widget_rich_checkbox_input)
        val checkbox = view.findViewById<AppCompatCheckBox>(R.id.widget_rich_checkbox)
        if (item == requestFocusItem) {
            input.requestFocus()
        }
        input.setOnKeyListener { _, keyCode, event ->
            logi("checkbox 按键事件:$keyCode")
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                logi("checkbox 新建一条")
                requestFocusItem = RichTodoItem()
                data.add(requestFocusItem!!)
                notifyItemInserted(data.size - 1)
                return@setOnKeyListener true
            }
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL) {
                if (input.text.isNullOrEmpty()) {
                    //删除当前
                    logi("当前组件无数据，可以删除当前的 checkbox组件 $position,all:${data.size}")
                    val s = data.indexOf(item)
                    if (s != -1) {
                        data.remove(item)
                        val updateFocusPosition = s - 1
                        notifyItemRemoved(s)
                        if (updateFocusPosition >= 0) {
                            notifyItemChanged(updateFocusPosition,1)
                        }
                        return@setOnKeyListener true
                    }
                }
            }
            false
        }
    }

    private val TAG = "适配器"

    override fun onAudioBind(item: RichAudioItem, view: View, position: Int) {

    }

}